package com.jcfk.eam.service.main;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jcfk.common.business.enums.DeleteFlag;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.eam.dao.base.EamRepairPlanDetailDao;
import com.jcfk.eam.domain.dto.base.*;
import com.jcfk.eam.domain.dto.main.EamAssetInfoDTO;
import com.jcfk.eam.domain.dto.main.EamInspectionPlanPersonDTO;
import com.jcfk.eam.domain.po.base.EamRepairPlanDetail;
import com.jcfk.eam.domain.po.base.EamRepairPlanDetailItem;
import com.jcfk.eam.domain.po.base.EamSparePart;
import com.jcfk.eam.domain.po.main.EamInspectionPlanPerson;
import com.jcfk.eam.domain.query.base.EamRepairPlanDetailContentQuery;
import com.jcfk.eam.domain.query.base.EamRepairPlanDetailImgQuery;
import com.jcfk.eam.domain.query.base.EamRepairPlanDetailQuery;
import com.jcfk.eam.service.base.EamAssetTypeService;
import com.jcfk.eam.service.base.EamRepairPlanDetailContentService;
import com.jcfk.eam.service.base.EamRepairPlanDetailImgService;
import com.jcfk.eam.service.base.EamSparePartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

/**
 * 计划维修明细
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2024-08-21
 */
@Service
public class EamRepairPlanDetailService extends BaseService<EamRepairPlanDetailDao, EamRepairPlanDetail> {


    @Autowired
    private EamRepairPlanDetailItemService eamRepairPlanDetailItemService;

    @Autowired
    private EamAssetInfoService eamAssetInfoService;

    @Autowired
    private EamSparePartService eamSparePartService;


    @Autowired
    private EamAssetTypeService eamAssetTypeService;


    @Autowired
    private EamInspectionPlanPersonService eamInspectionPlanPersonService;

    @Autowired
    private EamRepairOrderService eamRepairOrderService;

    @Autowired
    private EamRepairPlanDetailImgService eamRepairPlanDetailImgService;
    @Autowired
    private EamRepairPlanDetailContentService eamRepairPlanDetailContentService;


    /**
     * EamRepairPlanDetail分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamRepairPlanDetailDTO> queryByPage(DataPage<EamRepairPlanDetailDTO> page, EamRepairPlanDetailQuery query) {
        // 分页查询
        page = this.baseMapper.queryByPage(page, query);
        page.setRecords(fillUser(page.getRecords()));
        return page;
    }

    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<EamRepairPlanDetailDTO>
     */
    public List<EamRepairPlanDetailDTO> getList(EamRepairPlanDetailQuery query) {
        // 查询条件
        QueryWrapper<EamRepairPlanDetail> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getPlanId()), EamRepairPlanDetail::getPlanId, query.getPlanId());
        qw.eq("eamRepairPlanDetail.deleted", DeleteFlag.NOTDELETED.getValue());
        // 查询数据
        return fillUser(this.baseMapper.getList(qw));

    }

    private List<EamRepairPlanDetailDTO> fillUser(List<EamRepairPlanDetailDTO> list) {
        if (CollUtil.isEmpty(list)) return list;
        List<String> dtoIds = list.stream().map(EamRepairPlanDetailDTO::getId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(dtoIds)) {
            List<EamInspectionPlanPerson> eamInspectionPlanPeople = eamInspectionPlanPersonService.list(Wrappers.<EamInspectionPlanPerson>lambdaQuery()
                    .in(EamInspectionPlanPerson::getPlanId, dtoIds));
            Map<String, List<EamInspectionPlanPersonDTO>> eamInspectionPlanPersonMap = convertList(eamInspectionPlanPeople, EamInspectionPlanPersonDTO.class).stream()
                    .collect(Collectors.groupingBy(EamInspectionPlanPersonDTO::getPlanId));
            list.forEach(dto -> dto.setExecuteUsers(eamInspectionPlanPersonMap.get(dto.getId())));
        }
        return list;
    }

    /**
     * 获取根据关联id详情表列表
     *
     * @param query 查询条件
     * @return List<EamRepairPlanDetailDTO>
     */
    public List<EamRepairPlanDetailItemDTO> getDetails(EamRepairPlanDetailQuery query) {
        // 查询条件
        QueryWrapper<EamRepairPlanDetailItem> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getId()), EamRepairPlanDetailItem::getPlanDetailId, query.getId());

        // 查询数据
        List<EamRepairPlanDetailItem> list = eamRepairPlanDetailItemService.list(qw);

        List<String> ids = list.stream().map(EamRepairPlanDetailItem::getSparePartId).collect(Collectors.toList());

        List<EamRepairPlanDetailItemDTO> dtos = convertList(list, EamRepairPlanDetailItemDTO.class);

        if (ids.size() > 0) {
            QueryWrapper<EamSparePart> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", ids);
            List<EamSparePart> eamSpareParts = eamSparePartService.list(queryWrapper);
            Map<String, EamSparePart> map = new HashMap<>();
            for (EamSparePart eamSparePart : eamSpareParts) {
                map.put(eamSparePart.getId(), eamSparePart);
            }

            for (EamRepairPlanDetailItemDTO dto : dtos) {
                EamSparePart eamSparePart = map.get(dto.getSparePartId());
                if (eamSparePart != null) {
                    dto.setSpareCode(eamSparePart.getSpareCode());
                    dto.setSpareNmae(eamSparePart.getSpareNmae());
                    dto.setSpareType(eamSparePart.getSpareType());
                    dto.setSpareUnit(eamSparePart.getSpareUnit());
                }
            }
        }


        return dtos;
    }


    /**
     * 判断EamRepairPlanDetail是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EamRepairPlanDetailDTO dto) {
        QueryWrapper<EamRepairPlanDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        return RetResult.ok();
    }

    /**
     * 插入计划维修明细
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamRepairPlanDetailDTO dto) {

        // 保存
        EamRepairPlanDetail item = new EamRepairPlanDetail();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        super.save(item);

        // 设置关联主键
        for (EamRepairPlanDetailItemDTO detail : dto.getDetails()) {
            detail.setPlanDetailId(item.getId());
        }
        for (EamRepairPlanDetailImgDTO detail : dto.getImages()) {
            detail.setRepairPlanDetailId(item.getId());
        }
        for (EamRepairPlanDetailContentDTO detailType : dto.getTypes()) {
            detailType.setPlanDetailId(item.getId());
        }

        // 保存明细表
        eamRepairPlanDetailItemService.saveBatch(dto.getDetails(), item.getId());
        //保存明细图片
        eamRepairPlanDetailImgService.saveBatch(dto.getImages(), item.getId());
        //保存明细类型
        eamRepairPlanDetailContentService.saveBatch(dto.getTypes(), item.getId());
        // 保存维修人员
        saveInspectionPlanPerson(dto, item);
    }


    /**
     * 更新计划维修明细
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamRepairPlanDetailDTO dto) {

        // 保存
        EamRepairPlanDetail item = new EamRepairPlanDetail();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);

        // 设置关联主键
        for (EamRepairPlanDetailItemDTO detail : dto.getDetails()) {
            detail.setPlanDetailId(item.getId());
        }
        for (EamRepairPlanDetailImgDTO detail : dto.getImages()) {
            detail.setRepairPlanDetailId(item.getId());
        }
        for (EamRepairPlanDetailContentDTO detail : dto.getTypes()) {
            detail.setPlanDetailId(item.getId());
        }
        // 保存明细表
        eamRepairPlanDetailItemService.saveBatch(dto.getDetails(), item.getId());
        eamRepairPlanDetailImgService.saveBatch(dto.getImages(), item.getId());
        eamRepairPlanDetailContentService.saveBatch(dto.getTypes(), item.getId());
        // 保存维修人员
        saveInspectionPlanPerson(dto, item);
    }

    private void saveInspectionPlanPerson(EamRepairPlanDetailDTO dto, EamRepairPlanDetail item) {
        List<String> notExistUsers = new ArrayList<>();
        dto.getExecuteUsers().forEach(t -> {
            try {
                String userIdByEmpNo = eamRepairOrderService.getUserIdByEmpNo(t.getPersonEmpNo());
                t.setUserId(userIdByEmpNo);
                Assert.notEmpty(userIdByEmpNo);
            } catch (RuntimeException e) {
                notExistUsers.add(t.getPersonName());
            }
        });
        Assert.isTrue(CollUtil.isEmpty(notExistUsers), "未查询到:" + StrUtil.join(",", notExistUsers) + "人员信息");
        eamInspectionPlanPersonService.saveBatch(dto.getExecuteUsers(), item.getId());
    }


    /**
     * 根据批量主键删除计划维修明细(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EamRepairPlanDetailDTO dto) {

        EamRepairPlanDetail item = new EamRepairPlanDetail();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EamRepairPlanDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamRepairPlanDetail item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setVersion(1L);
            item.setDeleted(0);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());
    }


    /**
     * 根据主键获取计划维修明细信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamRepairPlanDetailDTO get(String id) {
        // 查询数据
        EamRepairPlanDetail item = this.baseMapper.selectById(id);
        EamRepairPlanDetailDTO dto = new EamRepairPlanDetailDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        EamAssetInfoDTO eamAssetInfoDTO = eamAssetInfoService.get(item.getAssetId());
        if (eamAssetInfoDTO != null) {
            dto.setAssetName(eamAssetInfoDTO.getAssetName());
            dto.setAssetCode(eamAssetInfoDTO.getAssetCode());
            dto.setUsingDepartmentId(eamAssetInfoDTO.getUsingDepartmentId());
            dto.setUsingDepartmentName(eamAssetInfoDTO.getUsingDepartmentName());
            dto.setLocationId(eamAssetInfoDTO.getLocationId());
            dto.setLocationName(eamAssetInfoDTO.getLocationName());
            dto.setAssetBrandName(eamAssetInfoDTO.getAssetBrandName());
            dto.setAssetModelNo(eamAssetInfoDTO.getAssetModelNo());
        }

        EamAssetTypeDTO eamAssetTypeDTO = eamAssetTypeService.get(eamAssetInfoDTO.getAssetTypeId());
        if (eamAssetTypeDTO != null) {
            dto.setAssetTypeCode(eamAssetTypeDTO.getAssetTypeCode());
            dto.setAssetTypeName(eamAssetTypeDTO.getAssetTypeName());
        }
        List<EamInspectionPlanPerson> eamInspectionPlanPeople = eamInspectionPlanPersonService.list(Wrappers.<EamInspectionPlanPerson>lambdaQuery()
                .eq(EamInspectionPlanPerson::getPlanId, item.getId()));
        dto.setExecuteUserIds(eamInspectionPlanPeople.stream().map(EamInspectionPlanPerson::getPersonId).collect(Collectors.toList()));
        dto.setExecuteUsers(convertList(eamInspectionPlanPeople, EamInspectionPlanPersonDTO.class));
        EamRepairPlanDetailImgQuery query = new EamRepairPlanDetailImgQuery();
        query.setRepairPlanDetailId(item.getId());
        List<EamRepairPlanDetailImgDTO> images = eamRepairPlanDetailImgService.getList(query);
        dto.setImages(images);
        EamRepairPlanDetailContentQuery eamRepairPlanDetailContentQuery = new EamRepairPlanDetailContentQuery();
        eamRepairPlanDetailContentQuery.setPlanDetailId(item.getId());
        dto.setTypes(eamRepairPlanDetailContentService.getList(eamRepairPlanDetailContentQuery));
        return dto;
    }


    /**
     * 根据主键获取计划维修明细信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteItem(String id) {
        EamRepairPlanDetail item = getById(id);
        this.setDefaultValue(item);
        item.setDeleted(1);

        this.updateById(item);
    }
}

